package syan.sql.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.google.common.base.Utf8;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import syan.sql.Dao.User;
import syan.sql.mapper.DivisionMapper;
import syan.sql.service.DivisionService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author CHENTAIWEN
 * @create 2022/9/23 10:47
 */
@Service
@Slf4j
public class DivisionServiceImpl implements DivisionService {

    @Autowired
    DivisionMapper divisionMapper;

    @Override
    public void update() {
        List<User> users = divisionMapper.queryUser();
        for (User user : users) {
            List<User> userList = divisionMapper.queryUserList(user.getId());
            for (var name : userList) {
                String divisionName = user.getName() + "-" + name.getName();
                name.setName(divisionName);
                divisionMapper.update(name);
                System.out.println(divisionName);
            }
        }
    }

    final int[] m = {3, 0};

    @Override
    public void exportExcel(HttpServletResponse response) {
        List<LinkedHashMap<String, Object>> dataList = divisionMapper.queryListMap();
        List<LinkedHashMap<String, Object>> listMap = divisionMapper.queryListMapS();
        try {
            ExcelWriter writer = ExcelUtil.getWriter();
            System.out.println("定义头模块");
            Map<String, String> headMap = this.execlWiter(writer);
            if (dataList.size() == 0) {
                System.out.println("数据为空");
                LinkedHashMap<String, Object> record = new LinkedHashMap<>();
                headMap.forEach((key, value) -> record.put(key, ""));
                dataList.add(record);
            }
            System.out.println("获取每个合同所占行数");
            List<LinkedHashMap<String, Object>> linkedHashMaps = new ArrayList<>();
            dataList.forEach(data -> {
                List<LinkedHashMap<String, Object>> linkedHashMap = this.leaseLine(data, listMap);
                linkedHashMaps.addAll(linkedHashMap);
            });
            System.out.println("合同总信息:" + linkedHashMaps);
            writer.setOnlyAlias(true);
            writer.passRows(2);
            writer.write(linkedHashMaps, true);
            writer.setRowHeight(0, 20);
            writer.setRowHeight(1, 20);
            //宽度
            for (int i = 0; i < headMap.size(); i++) {
                writer.setColumnWidth(i, 20);
            }
            Cell cell = writer.getCell(0, 0);
            CellStyle cellStyle = cell.getCellStyle();
//            cellStyle.setFillForegroundColor(IndexedColors.GOLD.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = writer.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 8);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            //合并
            dataList.forEach(data -> {
                Integer num = this.leaseLineNum(data, listMap);
                if (num > 1) {
                    this.excelline(writer, data, num);
                }
            });
            //自定义标题别名
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("2023年", "Utf-8")+".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
        } catch (Exception e) {
            log.error("导出合同错误：", e);
        }
    }

    private List<LinkedHashMap<String, Object>> leaseLine(LinkedHashMap<String, Object> data, List<LinkedHashMap<String, Object>> listMap) {
        System.out.println("合同：" + data.get("id"));
        Map<String, Integer> mapNum = new HashMap<>();
        List<Map<String, Object>> mapzj = new ArrayList<>();
        List<Map<String, Object>> mapzjyj = new ArrayList<>();
        List<Map<String, Object>> mapwy = new ArrayList<>();
        List<Map<String, Object>> mapsf = new ArrayList<>();
        List<Map<String, Object>> mapdf = new ArrayList<>();
        List<Map<String, Object>> mapktf = new ArrayList<>();
        Integer num = this.leaseLineNum(data, listMap);
        listMap.forEach(lst -> {
            if (lst.get("id").equals(data.get("id"))) {
                switch (String.valueOf(lst.get("expenseName"))) {
                    case "租金":
                        mapzj.add(lst);
                        break;
                    case "仓租押金":
                        mapzjyj.add(lst);
                        break;
                    case "物业管理费":
                        mapwy.add(lst);
                        break;
                    case "水费":
                        mapsf.add(lst);
                        break;
                    case "电费":
                        mapdf.add(lst);
                        break;
                    case "空调费":
                        mapktf.add(lst);
                        break;
                    case "电费押金":
                    case "水费押金":
                    case "空调押金":
                    default:
                        break;
                }
            }
        });
        System.out.println("合同：" + data.get("id") + "共计:" + mapNum + ",最大行数：" + num);
        System.out.println("合同信息：" + data);
        System.out.println("租金:" + mapzj);
        System.out.println("押金:" + mapzjyj);
        System.out.println("物业:" + mapwy);
        System.out.println("水费:" + mapsf);
        System.out.println("电费:" + mapdf);
        System.out.println("空调费:" + mapktf);
//        Map<String,Object>[] maps=new Map[]{};
        List<Map<String, Object>> mapsList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Map<String, Object> maps = new HashMap<>();
            if (mapzjyj.size() > i) {
                maps.put("zytaxIncluded", mapzjyj.get(i).get("taxIncluded"));
                maps.put("zunit", mapzjyj.get(i).get("paymentPeriod"));
            }
            if (mapzj.size() > i) {
                maps.put("zsquare", mapzj.get(i).get("square"));
                maps.put("ztaxIncluded", mapzj.get(i).get("taxIncluded"));
                maps.put("zpaymentPeriod", mapzj.get(i).get("paymentPeriod"));
            }
            if (mapwy.size() > i) {
//            maps.put("yytaxIncluded",mapzj.get(i).get("taxIncluded"));
//            maps.put("yunit",mapwy.get(i).get("paymentPeriod"));
                maps.put("ysquare", mapwy.get(i).get("square"));
                maps.put("ytaxIncluded", mapwy.get(i).get("taxIncluded"));
//                maps.put("ypaymentPeriod", mapwy.get(i).get("paymentPeriod"));
            }
            if (mapsf.size() > i) {
                mapssdf(maps, mapsf, "staxIncluded", "square", i);
            }
            if (mapdf.size() > i) {
                mapssdf(maps, mapdf, "ftaxIncluded", "square", i);
            }
            if (mapktf.size() > i) {
                mapssdf(maps, mapktf, "ktaxIncluded", "square", i);
            }
            System.out.println(maps);
            mapsList.add(maps);
        }
        System.out.println("合同金额列表:" + mapsList);
//        num个
        List<LinkedHashMap<String, Object>> linkedHashMaps = new ArrayList<>();
        mapsList.forEach(map -> {
            LinkedHashMap<String, Object> linkedHashMap = BeanUtil.copyProperties(data, LinkedHashMap.class);
            map.forEach((k, v) -> {
                linkedHashMap.put(k, v);
            });
            linkedHashMaps.add(linkedHashMap);
        });
        System.out.println("合同信息:" + linkedHashMaps);
        return linkedHashMaps;
    }

    private Map<String, Object> mapssdf(Map<String, Object> maps, List<Map<String, Object>> map, String key, String type, Integer i) {

        if ("月付".equals(map.get(i).get("paymentPeriod"))) {
            maps.put(key, "月付" + map.get(i).get(type));
        } else if (" ".equals(map.get(i).get("paymentPeriod"))) {
            maps.put(key, "一次性" + map.get(i).get(type));
        } else {
            maps.put(key, map.get(i).get(type));
        }
        return maps;
    }

    private Integer leaseLineNum(LinkedHashMap<String, Object> data, List<LinkedHashMap<String, Object>> listMap) {
        Map<String, Integer> mapNum = new HashMap<>();
        listMap.forEach(lst -> {
            if (lst.get("id").equals(data.get("id"))) {
                Integer j = mapNum.get(String.valueOf(lst.get("expenseName")));
                mapNum.put(String.valueOf(lst.get("expenseName")), j == null ? 1 : ++j);
            }
        });
        int length = mapNum.size();
        Collection<Integer> c = mapNum.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        Integer num = Integer.valueOf(String.valueOf(obj[length - 1]));
        return num;
    }

    private void excelline(ExcelWriter writer, LinkedHashMap<String, Object> data, Integer num) {
        m[1] = 0;
        data.forEach((k, v) -> {
            if (!"id".equals(k)) {
                if (ObjectUtil.isNotEmpty(v)) {
                    writer.merge(m[0], m[0] + num - 1, m[1], m[1], v, false);
                }
                m[1]++;
            }
        });
        m[0] += num;
    }

    private Map<String, String> execlWiter(ExcelWriter writer) {
        writer.merge(0, 0, 0, 21, "仓库租赁信息", false);
        writer.merge(1, 2, 0, 0, "区域", false);
        writer.merge(1, 2, 1, 1, "项目", false);
        writer.merge(1, 2, 2, 2, "承租方", false);
        writer.merge(1, 2, 3, 3, "出租房", false);
        writer.merge(1, 2, 4, 4, "地址", false);
        writer.merge(1, 2, 5, 5, "面积", false);
        writer.merge(1, 2, 6, 6, "单位", false);
        writer.merge(1, 2, 7, 7, "币种", false);
        writer.merge(1, 1, 8, 12, "租金(月)", false);
        writer.merge(1, 1, 13, 17, "物业管理费(月)", false);
        writer.merge(1, 1, 18, 21, "水电费", false);
        writer.merge(1, 1, 22, 23, "合同期限", false);
        writer.merge(1, 2, 24, 24, "合同情况", false);

        Map<String, String> headMap = new LinkedHashMap<>();
        headMap.put("region", "区域");
        headMap.put("item", "项目");
        headMap.put("paymentCompany", "承租方");
        headMap.put("supplierName", "出租房");
        headMap.put("address", "地址");
        headMap.put("area", "面积");
        headMap.put("unit", "单位");
        headMap.put("currency", "币种");

        headMap.put("zytaxIncluded", " 押金(元)");
        headMap.put("zunit", " 押金方式");
        headMap.put("zsquare", " 单价/平方");
        headMap.put("ztaxIncluded", " 金额");
        headMap.put("zpaymentPeriod", " 付款周期");

        headMap.put("yytaxIncluded", "押金(元) ");
        headMap.put("yunit", "押金方式 ");
        headMap.put("ysquare", "单价/平方 ");
        headMap.put("ytaxIncluded", "金额 ");
        headMap.put("ypaymentPeriod", "付款周期 ");

        headMap.put("staxIncluded", "水费金额(元/吨)");
        headMap.put("ftaxIncluded", "电费金额(元/度)");
        headMap.put("ktaxIncluded", "空调电费(元/度)");
        headMap.put("sdpaymentPeriod", "付款周期");

        headMap.put("startTime", "起");
        headMap.put("endTime", "止");
        headMap.put("review", "合同情况");

        headMap.forEach(writer::addHeaderAlias);

        return headMap;
    }

/*
    @Override
    public void exportExcel(HttpServletResponse response)  {
        List<LinkedHashMap<String, Object>> dataList =divisionMapper.queryList();
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            Map<String,String> headMap = new LinkedHashMap<>();
            headMap.put("region","区域");
            headMap.put("item","项目");
            headMap.put("paymentCompany","承租方");
            headMap.put("supplierName","出租房");
            headMap.put("address","地址");
            headMap.put("area","面积");
            headMap.put("unit","单位");
            headMap.put("currency","币种");

            headMap.put("zytaxIncluded"," 押金(元)");
            headMap.put("zunit"," 押金方式");
            headMap.put("zsquare"," 单价/平方");
            headMap.put("ztaxIncluded"," 金额");
            headMap.put("zpaymentPeriod"," 付款周期");

            headMap.put("yytaxIncluded","押金(元) ");
            headMap.put("yunit","押金方式 ");
            headMap.put("ysquare","单价/平方 ");
            headMap.put("ytaxIncluded","金额 ");
            headMap.put("ypaymentPeriod","付款周期 ");

            headMap.put("staxIncluded","水费金额(元/吨)");
            headMap.put("ftaxIncluded","电费金额(元/度)");
            headMap.put("ktaxIncluded","空调电费(元/度)");
            headMap.put("sdpaymentPeriod","付款周期");

            headMap.put("startTime","起");
            headMap.put("endTime","止");
            headMap.put("review","合同情况");


            writer.merge(0,0,0,21, "仓库租赁信息",false);
            writer.merge(0,0,22,24,"某年",false);

            writer.merge(1,2,0,0,"区域",false);
            writer.merge(1,2,1,1,"项目",false);
            writer.merge(1,2,2,2,"承租方",false);
            writer.merge(1,2,3,3,"出租房",false);
            writer.merge(1,2,4,4,"地址",false);
            writer.merge(1,2,5,5,"面积",false);
            writer.merge(1,2,6,6,"单位",false);
            writer.merge(1,2,7,7,"币种",false);
            writer.merge(1,1,8,12,"租金(月)",false);
            writer.merge(1,1,13,17,"业务管理费(月)",false);
            writer.merge(1,1,18,21,"水电费(月)",false);
            writer.merge(1,1,22,23,"合同期限",false);
            writer.merge(1,2,24,24,"合同情况",false);
            headMap.forEach(writer::addHeaderAlias);
            if (dataList.size() == 0) {
                LinkedHashMap<String, Object> record = new LinkedHashMap<>();
                headMap.forEach((key, value) -> record.put(key, ""));
                dataList.add(record);
            }
            writer.setOnlyAlias(true);
            writer.passRows(2);
            writer.write(dataList, true);
            LinkedHashMap<String, Integer> mapNum =new LinkedHashMap<>();
            List<LinkedHashMap<String,Object>>mapList=new ArrayList<>();
            //获取合并几个单元格
            Long doNotMerge=System.currentTimeMillis();
            dataList.forEach(data->{
                Integer j=mapNum.get(data.get("id"));
                mapNum.put(data.get("id").toString(),j==null?1:++j);
                //获取同一id重复的数据
                dataList.forEach(databody->{
                    if (data.get("id").equals(databody.get("id"))&& !data.equals(databody)){
                        //获取不可合并的数据
                        LinkedHashMap<String,Object> linkedHashMap=new LinkedHashMap<>();
                        for (var databodyMap :databody.entrySet()){
                            if (data.get(databodyMap.getKey()).equals(databodyMap.getValue())){
                                linkedHashMap.put(databodyMap.getKey(),databodyMap.getValue());
                            }else{
                                linkedHashMap.put(databodyMap.getKey(),doNotMerge);
                            }
                        }
                        mapList.add(linkedHashMap);
                    }
                });

            });
            System.out.println(mapNum);
            writer.setRowHeight(0, 20);
            writer.setRowHeight(1, 20);
            //宽度
            for (int i = 0; i < headMap.size(); i++) {
                writer.setColumnWidth(i, 20);
            }
            Cell cell = writer.getCell(0, 0);
            CellStyle cellStyle = cell.getCellStyle();
//            cellStyle.setFillForegroundColor(IndexedColors.GOLD.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = writer.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 8);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            final int[] m={3,0};
            //去重
            List<LinkedHashMap<String, Object>> finalMapList = mapList.stream().distinct().collect(Collectors.toList());
            mapNum.forEach((key1, value1) -> {
                //行 起止 列起止 内容 样式
                for (var finalMap : finalMapList) {
                    if (finalMap.get("id").equals(key1)) {
                        m[1] = 0;
                        finalMap.forEach((key, value) -> {
                            if (value1>1 && !"id".equals(key)) {
                                if (!value.equals(doNotMerge)) {writer.merge(m[0], m[0] + value1 - 1, m[1], m[1], value, false);}
                                m[1]++;
                                System.out.println(value);
                            }
                        });
                    }
                }
                m[0] += value1;
            });
            //自定义标题别名
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=Lease.xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
        } catch (Exception e) {
            log.error("导出合同错误：", e);
        }
    }*/
}
